package com.example.demo.webtest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 测试web类
 *
 * @date： 2022/2/28
 * @author: wbx
 */
@RestController
public class WebTestController {
    @Resource
    HttpServletRequest request;

    private final String headerKey = "headerKey";

    @PostMapping("/testWeb")
    public void testWeb() {
        String header = request.getHeader(headerKey);
        System.out.println("testWeb ====>" + header);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 设置子线程共享(只要 request未结束 所有子线程共享)
        RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
        String s = runAsync();
        System.out.println(s);
    }

    // 子线程一
    private String runAsync() {
        String result = "";
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            // 子线程1获取request请求头信息
            return "runAsync：header==>" + request.getHeader(headerKey);
        });
        try {
            result = completableFuture.get();
            completableFuture.whenCompleteAsync((res , e) -> {
                String s = runAsync123();
                System.out.println("runAsync123");
            });
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 子线程二
    private String runAsync123() {
        String result = "";
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            // 子线程2获取request请求头信息
            System.out.println("runAsync123" + "开始执行！");
            return "runAsync123：header==>" + request.getHeader(headerKey);
        });
        try {
            Thread.sleep(5000);
            result = completableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return result;
    }
}
